<template>
  <div class="alarm-container">
    <div class="content">
      <div class="search">
        <cq-region v-model="state.queryParams.regionCodes"></cq-region>
        <van-dropdown-menu
          ref="menuRef"
          :close-on-click-overlay="false"
          :close-on-click-outside="false"
        >
          <van-dropdown-item ref="itemRef">
            <template #title>
              <span class="filter-o"><van-icon name="filter-o" size="20" /></span>
            </template>

            <div class="filter-content">
              <van-form ref="formRef">
                <van-cell-group>
                  <van-field
                    v-model="state.formData.rainfallCycleName"
                    label="降雨轮次"
                    @click="querySelect('rainfallCycle')"
                    placeholder="请选择降雨轮次"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    style="width: 50%"
                  />
                  <van-field
                    v-model="state.formData.tjDate"
                    label="预警时段"
                    @click="state.datePicker1 = true"
                    placeholder="请选择预警时段"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    style="width: 50%"
                  />

                  <van-field
                    v-model="state.formData.warningLevel"
                    label="预警等级"
                    @click="querySelect('warningLevel')"
                    placeholder="请选择预警等级"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    style="width: 50%"
                  />
                  <van-field
                    v-model="state.formData.reqState"
                    label="叫应状态"
                    @click="querySelect('reqState')"
                    placeholder="请选择叫应状态"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    style="width: 50%"
                  />
                  <van-field
                    v-model="state.formData.respState"
                    label="响应状态"
                    @click="querySelect('respState')"
                    placeholder="请选择响应状态"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    style="width: 50%"
                  />

                  <van-field
                    v-model="state.formData.cyBasic"
                    label="预警依据"
                    @click="querySelect('cyBasic')"
                    placeholder="请选择预警依据"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    style="width: 50%"
                  />

                  <van-field
                    v-model="state.formData.cyType"
                    label="预警类型"
                    @click="querySelect('cyType')"
                    placeholder="请选择预警类型"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    style="width: 50%"
                  />
                  <van-field
                    v-model="state.formData.isDrillName"
                    name="region"
                    label="是否演练"
                    @click="querySelect('isDrill')"
                    style="width: 50%"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    placeholder="请选择是否演练"
                  />
                </van-cell-group>
              </van-form>
            </div>

            <div style="padding: 5px 10px">
              <van-button type="primary" block @click="onFirm">确认</van-button>
              <van-button style="margin-top: 5px" block @click="onReset">重置</van-button>
            </div>
          </van-dropdown-item>
        </van-dropdown-menu>
      </div>
    </div>
    <div class="button-group">
      <van-button
        round
        :type="state.active == item.name ? 'primary' : 'default'"
        v-for="(item, index) in state.buttonGroup"
        :key="index"
        @click="handleChange(item.name)"
        style="margin-right: 12px"
        >{{ item.name }}</van-button
      >
    </div>

    <div class="alarm-list" ref="listContainer">
      <van-pull-refresh v-model="refreshing" @refresh="onLoad('refresh')">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div class="alarm-item" v-for="(item, index) in state.alarmList" :key="index">
            <div class="alarm-header">
              <van-image width="24" height="24" fit="cover" round :src="locationIcon" />
              <span class="t1">{{ item.cyPlace }}</span>
              <span class="t2">{{ item.cyRainTime }}</span>
              <span
                class="t3"
                :style="{
                  color: getColor(item.cyWaringLevel),
                  borderColor: getColor(item.cyWaringLevel),
                }"
                >{{ MAP_STATE.cyWaringLevel[item.cyWaringLevel] }}</span
              >
            </div>
            <div class="alarm-content">
              <div class="c1">
                {{ item.cyWaringName }}
              </div>
              <div class="c2">
                {{ item.cyWaringDetail }}
              </div>
              <div class="line"></div>

              <div class="status" v-if="state.queryParams.type == '2'">
                <div>
                  预警状态
                  <span
                    :style="{
                      color: MAP_STATE.cyState[item.cyState] == '已生效' ? '#007FFF' : '',
                    }"
                    >{{ MAP_STATE.cyState[item.cyState] }}</span
                  >
                </div>
                <div>
                  响应状态
                  <span
                    :style="{
                      color:
                        MAP_STATE.cyResState[item.cyResState] == '已响应'
                          ? '#007FFF'
                          : '',
                    }"
                    >{{ MAP_STATE.cyResState[item.cyResState] }}</span
                  >
                </div>
                <div>
                  叫应状态
                  <span
                    :style="{
                      color:
                        MAP_STATE.cyReqState[item.cyReqState] == '已叫应'
                          ? '#007FFF'
                          : '',
                    }"
                    >{{ MAP_STATE.cyReqState[item.cyReqState] }}</span
                  >
                </div>
                <div>
                  是否演练 <span>{{ MAP_STATE.isDo[item.isDo] }}</span>
                </div>
                <div>{{ item.timeStart }}-{{ item.timeEnd }}</div>
              </div>

              <div class="status point" v-else>
                <div>
                  降水量 <span>{{ item.twoHourRain }}毫米</span>
                </div>
                <div>
                  预警阈值 <span>{{ item.cyRainNum }}毫米</span>
                </div>
                <div>
                  响应状态
                  <span
                    :style="{
                      color:
                        MAP_STATE.cyResState[item.cyResState] == '已响应'
                          ? '#007FFF'
                          : '',
                    }"
                    >{{ MAP_STATE.cyResState[item.cyResState] }}</span
                  >
                </div>
                <div>
                  是否演练 <span>{{ MAP_STATE.isDo[item.isDo] }}</span>
                </div>
                <div>{{ item.cyTimes }}</div>
              </div>

              <div class="confirm" v-if="state.queryParams.type == '2'">
                <van-button
                  type="primary"
                  block
                  :disabled="item.cyReqState == '1'"
                  @click="handleCall(item)"
                  >叫应</van-button
                >
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

    <van-overlay :show="state.show" style="z-index: 2000">
      <div class="wrapper">
        <div class="block">
          <div class="title">叫应后会生成响应任务请及时处理</div>
          <div class="buttons">
            <van-button
              style="background-color: #e6f7ff; color: #1890ff; width: 50%"
              @click="state.show = false"
              >取消</van-button
            >
            <van-button type="primary" style="width: 50%" @click="handleConfirm"
              >确认叫应</van-button
            >
          </div>
        </div>
      </div>
    </van-overlay>

    <van-popup v-model:show="state.showPicker" destroy-on-close position="bottom">
      <van-picker
        :columns="state.columns"
        :model-value="state.pickerValue"
        @confirm="onPicker"
        @cancel="state.showPicker = false"
      />
    </van-popup>

    <van-popup v-model:show="state.datePicker1" destroy-on-close position="bottom">
      <van-date-picker
        title="选择日期"
        @confirm="changeDay"
        @cancel="state.datePicker1 = false"
        :min-date="minDate"
        :max-date="maxDate"
      >
        <van-date-picker v-model="state.formData.startDate" />
      </van-date-picker>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, reactive } from "vue";
import locationIcon from "@/assets/images/task/icon_region_location.png";
import {
  getAlarmEventListApi,
  countyCallingApi,
  getConditionsApi,
} from "@/api/eventTask";
import CqRegion from "@/components/CqRegion.vue";
const state = reactive({
  active: "区域预警",
  buttonGroup: [
    {
      name: "区域预警",
    },
    {
      name: "点位预警",
    },
  ],
  alarmList: [],
  show: false,
  queryParams: {
    current: 1,
    size: 10,
    type: 2, // 1:点位预警，2：区域预警
    dataType: 1, //1:当前数据，2：历史数据
  },
  pages: 0,
  // 叫应id
  callId: "",
  formData: {},
  datePicker1: false,
});

const maxDate = new Date(2025, 11, 31); //最大日期
const minDate = new Date(2025, 0, 1); //最小日期
// 分页参数
const refreshing = ref(false);
const loading = ref(false);
const finished = ref(false);

const listContainer = ref(null);
// 点击预警按钮
const handleChange = (val) => {
  state.active = val;
  // state.queryParams.current = 1;
  state.queryParams = {
    current: 1,
    pageSize: 10,
    dataType: 1,
    type: state.active == "区域预警" ? 2 : 1,
  };
  getAlarmEventListFn();
  state.pickerValue = [];
  state.pickerType = "";
  state.columns = [];
  state.formData = {};
  // if (val == "区域预警") {
  //   state.queryParams.type = 2;
  //   getAlarmEventListFn();
  // } else {
  //   state.queryParams.type = 1;
  //   getAlarmEventListFn();
  // }

  // 滚动到顶部
  listContainer.value.scrollTop = 0;
};

// 点击叫应
const handleCall = (item) => {
  state.show = true;
  state.callId = item.id;
};
// 点击确认呼应
const handleConfirm = async () => {
  state.show = false;
  await countyCallingApi(state.callId);
  getAlarmEventListFn();
};

// 获取列表
const getAlarmEventListFn = () => {
  loading.value = true;
  getAlarmEventListApi(state.queryParams)
    .then(({ data }) => {
      if (data && data.code == 200) {
        state.pages = Math.ceil(data.data.total / state.queryParams.size);

        let list = data.data.records || [];

        if (state.queryParams.current == 1) {
          state.alarmList = list;
        } else {
          state.alarmList = state.alarmList.concat(list);
        }
        if (state.queryParams.current == state.pages || state.pages == 0) {
          finished.value = true;
        }
      } else {
        finished.value = true;
      }
    })
    .catch((err) => {
      finished.value = true;
    })
    .finally(() => {
      loading.value = false;
    });
};

const onLoad = (type) => {
  if (type === "refresh") {
    finished.value = false;
    loading.value = true;
  }

  if (refreshing.value || type === "refresh") {
    state.pages = 0;
    state.queryParams.current = 1;
    state.alarmList.value = [];
    refreshing.value = false;
  }

  if (type !== "refresh") {
    if (state.queryParams.current >= state.pages) return;
    state.queryParams.current++;
  }
  getAlarmEventListFn();
};
// 状态映射
const MAP_STATE = {
  // 风险等级
  cyWaringLevel: {
    1: "高风险",
    2: "中风险",
    3: "低风险",
    4: "无风险",
  },
  // 预警状态
  cyState: {
    1: "已生效",
    0: "已失效",
    "-1": "未发布",
  },
  // 响应状态
  cyResState: {
    0: "未响应",
    1: "已响应",
  },
  // 叫应状态
  cyReqState: {
    0: "未叫应",
    1: "已叫应",
  },
  // 是否演练
  isDo: {
    0: "否",
    1: "是",
  },
};

// 根据状态返回颜色
const getColor = (key) => {
  switch (key) {
    case "1":
      return "#FF4D4F";
    case "2":
      return "#FC9C00";
    case "3":
      return "#00b042";
    case "4":
      return "rgba(0,0,0,0.4)";
    default:
      break;
  }
};
// 降雨轮次下拉
const rainfallCycleOptions = ref([]);
// 风险等级下拉
const cqWarningLevelOptions = [
  {
    text: "高风险",
    value: "1",
  },
  {
    text: "中风险",
    value: "2",
  },
  {
    text: "低风险",
    value: "3",
  },
  {
    text: "无风险",
    value: "4",
  },
];

// 叫应状态下拉
const cyReqStateOptions = [
  {
    text: "已叫应",
    value: "1",
  },
  {
    text: "未叫应",
    value: "0",
  },
];

// 响应状态下拉
const cyRespStateOptions = [
  {
    text: "已响应",
    value: "1",
  },
  {
    text: "未响应",
    value: "0",
  },
];

// 预警依据下拉
const cyBasicOptions = [
  {
    text: "重要气象专报",
    value: "1",
  },

  {
    text: "每日气象要讯",
    value: "2",
  },

  {
    text: "6h暴雨预警",
    value: "3",
  },
  {
    text: "未来2h累计降雨量超阈值",
    value: "4",
  },
];

// 预警类型下拉
const cyType = [
  {
    text: "区域气象自动预警",
    value: "0",
  },

  {
    text: "区域人工预警",
    value: "1",
  },
];

// 是否演练下拉
const isDrillOptions = [
  {
    text: "是",
    value: "1",
  },
  {
    text: "否",
    value: "0",
  },
];
// 点击查询条件
const querySelect = (type) => {
  if (type === "warningLevel") {
    state.columns = cqWarningLevelOptions;
  } else if (type === "reqState") {
    state.columns = cyReqStateOptions;
  } else if (type === "respState") {
    state.columns = cyRespStateOptions;
  } else if (type === "rainfallCycle") {
    state.columns = rainfallCycleOptions;
  } else if (type === "isDrill") {
    state.columns = isDrillOptions;
  } else if (type === "cyBasic") {
    state.columns = cyBasicOptions;
  } else if (type === "cyType") {
    state.columns = cyType;
  }
  state.showPicker = true;
  state.pickerType = type;
};
// 选择下拉弹窗
const onPicker = ({ selectedValues, selectedOptions }) => {
  switch (state.pickerType) {
    case "warningLevel":
      state.queryParams.cyWaringLevel = selectedOptions[0].value;
      state.formData.warningLevel = selectedOptions[0].text;
      break;
    case "isDrill":
      // state.formData.isDrill = selectedValues[0].value;
      state.queryParams.isDo = selectedOptions[0].value;
      state.formData.isDrillName = selectedOptions[0].text;
      break;
    case "reqState":
      // state.formData.workType = selectedValues[0].value;
      state.queryParams.cyReqState = selectedOptions[0].value;
      state.formData.reqState = selectedOptions[0].text;
      break;
    case "respState":
      // state.formData.rainfallCycle = selectedValues[0].value;
      state.queryParams.cyResState = selectedOptions[0].value;
      state.formData.respState = selectedOptions[0].text;

      break;
    case "cyBasic":
      // state.formData.rainfallCycle = selectedValues[0].value;
      state.queryParams.cyBasis = selectedOptions[0].value;
      state.formData.cyBasic = selectedOptions[0].text;
      break;
    case "cyType":
      // state.formData.rainfallCycle = selectedValues[0].value;
      state.queryParams.cyType = selectedOptions[0].value;
      state.formData.cyType = selectedOptions[0].text;
      break;
    case "rainfallCycle":
      state.queryParams.rainfallCycle = selectedOptions[0].value;
      state.formData.rainfallCycleName = selectedOptions[0].text;
      break;
    case "warningLevel":
      state.queryParams.level = selectedOptions[0].value;
      state.formData.levelName = selectedOptions[0].text;
      break;
    default:
      break;
  }
  //分类型选择器确定
  state.pickerValue = selectedValues;
  state.showPicker = false;
};
// 获取降雨轮次下拉
const getConditions = async () => {
  const { data } = await getConditionsApi();
  if (data && data.code == 200) {
    rainfallCycleOptions.value =
      data.data?.rain_times.map((item) => {
        return {
          text: item,
          value: item,
        };
      }) || [];
  }
};

// 选择预警时段
const changeDay = ({ selectedValues }) => {
  state.formData.tjDate = selectedValues.join("-");
  state.queryParams.cyTimes = selectedValues.join("-");
  state.datePicker1 = false;
};
const menuRef = ref(null);
// 确认
const onFirm = () => {
  state.queryParams.current = 1;
  getAlarmEventListFn();
  menuRef.value.close();
};

// 重置
const onReset = () => {
  state.queryParams = {
    current: 1,
    pageSize: 10,
    dataType: 1,
    type: state.active == "区域预警" ? 2 : 1,
  };
  state.pickerValue = [];
  state.pickerType = "";
  state.columns = [];
  state.formData = {};
  getAlarmEventListFn();
  menuRef.value.close();
};

onMounted(() => {
  getConditions();
  getAlarmEventListFn();
});
</script>

<style lang="less" scoped>
.alarm-container {
  height: 100%;
  .content {
    background: rgba(243, 243, 243, 1);
    margin-bottom: 10px;
    .search {
      height: 30px;
      display: flex;
      justify-content: space-between;
      .van-field {
        width: calc(100% - 40px);
        background: #fff;
        height: 100%;
        display: flex;
        align-items: center;
        padding: 0 10px;
        margin-bottom: 10px;
      }
      :deep(.van-dropdown-menu__bar) {
        background: #fff;
        margin-left: 10px;
        height: 30px;
        width: 30px;
        .van-dropdown-menu__title {
          padding: 0;
        }
        .van-dropdown-menu__title:after {
          display: none;
        }
        .van-dropdown-menu__title--down:after {
          display: none;
        }
      }
      :deep(.van-dropdown-item) {
        top: 150px !important;
      }
      .filter-o {
        height: 30px;
        width: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .filter-content {
        padding: 10px 0;
        width: 100%;
        .van-form {
          display: flex;
          flex-wrap: wrap;
        }
        :deep(.van-cell-group) {
          display: flex;
          flex-wrap: wrap;
        }
        :deep(.van-field) {
          width: 100%;
          height: auto;
          .van-field__value {
            background: #f2f2f2;
            height: 40px;
            display: flex;
            align-items: center;
            padding: 0 10px;
            .van-field__body {
              width: 100%;
            }
          }
        }
      }
    }
  }
  .alarm-list {
    margin-top: 12px;
    height: calc(100% - 50px);
    overflow-y: auto;
    .alarm-item {
      background: #ffffff;
      border-radius: 8px 8px 8px 8px;
      margin-bottom: 12px;
      .alarm-header {
        height: 36px;
        width: 100%;
        background: linear-gradient(
          90deg,
          rgba(0, 127, 255, 0.08) 0%,
          rgba(0, 127, 255, 0) 100%
        );
        display: flex;
        padding-top: 8px;
        padding-left: 12px;
        padding-right: 12px;
        box-sizing: border-box;
        span {
          margin-top: 2px;
        }
        font-family: PingFang TC, PingFang TC;

        .t1 {
          font-weight: 600;
          font-size: 12px;
          color: rgba(0, 0, 0, 0.9);
          margin-left: 4px;
        }

        .t2 {
          font-weight: 400;
          font-size: 12px;
          color: rgba(0, 0, 0, 0.6);
          margin-left: 12px;
        }

        .t3 {
          border-radius: 4px 4px 4px 4px;
          border: 1px solid #00b042;
          color: #00b042;
          text-align: center;
          padding: 0 4px;
          height: 18px;
          margin-left: auto;
        }
      }

      .alarm-content {
        padding: 8px 12px 12px 12px;
        font-family: PingFang TC, PingFang TC;
        .c1 {
          font-weight: 600;
          font-size: 16px;
          color: rgba(0, 0, 0, 0.9);
        }

        .c2 {
          font-weight: 400;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.6);
          margin-top: 4px;
          // white-space: nowrap; /* 防止文本换行 */
          // overflow: hidden; /* 隐藏超出部分 */
          // text-overflow: ellipsis; /* 超出部分显示省略号 */
        }

        .line {
          border: 1px solid #e7e7e7;
          margin: 8px 0;
        }

        .status {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 8px 18px;
          font-family: PingFang TC, PingFang TC;
          font-weight: 400;
          font-size: 12px;
          color: rgba(0, 0, 0, 0.4);
          div:nth-child(1) {
            span {
              color: rgba(0, 0, 0, 0.9);
            }
          }
          div {
            span {
              color: rgba(245, 34, 45, 1);
            }
          }
          div:last-child {
            grid-column: span 2; // 可调整为 span 2 或 span 3 来占用更多列
            width: 100%; // 根据需要可选
            text-align: right;
          }
        }

        .status.point {
          grid-template-columns: 100px 110px 100px;
          gap: 8px;
          div:nth-child(2) {
            span {
              color: rgba(0, 127, 255, 1);
            }
          }
          div {
            span {
              color: rgba(245, 34, 45, 1);
            }
          }
        }

        .confirm {
          width: 100%;
          margin-top: 8px;
        }
      }
    }
  }
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;

  .block {
    width: 300px;
    // height: 160px;
    background: #ffffff;
    border-radius: 12px 12px 12px 12px;
    padding: 24px;
    box-sizing: border-box;
    text-align: center;
    .title {
      font-family: PingFang TC, PingFang TC;
      font-weight: 600;
      font-size: 18px;
      color: rgba(0, 0, 0, 0.9);
    }

    .buttons {
      margin-top: 24px;
      display: flex;
      gap: 12px;
    }
  }
}
</style>
